import { useRef, useState, useEffect } from "react";
import { UploadHeader } from "../../components/Upload/UploadHeader";
import { useNavigate } from "react-router-dom";
import { Button, Form, Input, Radio, Row, Col } from "antd";
import { AiEditor } from "aieditor";
import { GetUserSeries,insertIntoArticles } from '../../api/Upload/index';
import { UploadFormSeries } from "../../components/Upload/UploadForm";
import "aieditor/dist/style.css";
import LoginStore from "../../store/Login/index";
import { success,error } from "../../utils/Notification";
const Upload = () => {

  const [form] = Form.useForm();//表单实例

  const { userInfo } = LoginStore();//获取用户信息

  const navigate = useNavigate();//路由导航

  const [isClick,setIsClick]=useState(false);//按钮点击状态

  const [seriesDataList, setSeriesDataList] = useState([]);//文章系列数据存储

  const [seriesType, setSeriesType] = useState({
    userId: userInfo.id,
    columnId: "1",
    cateId: "1",
    seriesId: "1",
    scopeId: "1"
  });//文章crud-pointer
  /*
    @Author: matrix
    @Description: 富文本编辑器
  */
  const divRef = useRef(null);

  const aiEditorRef = useRef(null);

  const [html, setHTML] = useState('');

  useEffect(() => {

    GetUserSeries({//获取用户系列数据
      "userId": userInfo.id,
      "columnId": null,
      "cateId": null
    }).then(res => {
      console.log(res.data.data);
      setSeriesDataList(res.data.data);
    })

    if (divRef.current) {
      const aiEditor = new AiEditor({
        element: divRef.current,
        placeholder: "Click to Input Content...",
        content: '',
      })
      aiEditorRef.current = aiEditor;
      return () => {
        aiEditor.destroy();
      }
    }
  }, [])

  const onSubmit = ()=>{//提交函数
    const content = aiEditorRef.current.getMarkdown(); // 获取富文本内容

    setHTML(content);

    console.log({
      title:form.getFieldValue('title'),
      content:html,
      seriesId:seriesType.seriesId,
      scopeId:seriesType.scopeId,
    });

    if(!isClick){
      error('上传失败','请在1秒后重新上传');

      setIsClick(true);

      return;
    }

    insertIntoArticles({
      title:form.getFieldValue('title'),
      content:html,
      // columnId:seriesType.columnId,
      // cateId:seriesType.cateId,
      seriesId:seriesType.seriesId,
      scopeId:seriesType.scopeId,
    },userInfo.id).then((res)=>{ 
      if(res.data.code===200){
        success(res.data.msg,res.data.data);

        setTimeout(()=>{
          
          navigate(-1);
          
        },3000)
      }else{
        error('上传失败');
      }
    })


  }

  const onFinishFailed = (errorInfo) => {//提交失败
    console.log('Failed:', errorInfo);
  }
  return (
    <>
      <UploadHeader goBack={() => navigate(-1)} />
      <div className="mt-10 w-4/5 mx-auto">
        <Form
          form={form}
          name="uploadForm"
          onFinish={onSubmit}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Row>
            <Col span={12}>
              <Form.Item
                label="文章标题"
                name="title"
                rules={[{ required: true, message: 'Please input your title!' }]}
              >
                <Input placeholder="请输入文章标题" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="content">
            <div ref={divRef} style={{ height: "400px" }} />
          </Form.Item>

          <Form.Item
            label="文章专栏"
            name="columnId"
          >
            <Radio.Group size="large" onChange={(e) => {
              setSeriesType((prev) => {
                prev.columnId = e.target.value;
                GetUserSeries(seriesType).then(res => {
                  setSeriesDataList(res.data.data);
                })
                console.log(seriesType);
                return prev;
              })//e.target.value
            }}>
              <Radio.Button value="1">后端</Radio.Button>
              <Radio.Button value="2">前端</Radio.Button>
              <Radio.Button value="3">服务端</Radio.Button>
            </Radio.Group>
          </Form.Item>


          <Form.Item
            label="文章分类"
            name="cateId"
          >
            <Radio.Group size="large" onChange={
              (e) => {
                setSeriesType((prev) => {
                  prev.cateId = e.target.value;
                  GetUserSeries(seriesType).then(res => {
                    setSeriesDataList(res.data.data);
                  })
                  console.log(seriesType);
                  return prev;
                })//e.target.value
              }
            }>
              <Radio.Button value="1">技术文章</Radio.Button>
              <Radio.Button value="2">干货内容</Radio.Button>
              <Radio.Button value="3">八股文章</Radio.Button>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="文章系列"
            name="series"
          >
            <Radio.Group size="large" onChange={
              (e) => {
                setSeriesType((prev) => {
                  prev.seriesId = e.target.value;
                  console.log(seriesType);
                  return prev;
                })//e.target.value
              }
            }>
              <UploadFormSeries list={seriesDataList}></UploadFormSeries>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="可见范围"
            name="scope"
          >
            <Radio.Group
              size="large"
              options={[{
                value: 1,
                label: '全平台可见'
              },
              {
                value: 2,
                label: '仅自己可见'
              }]}
              onChange={(e) => {
                setSeriesType((prev) => {
                  prev.scopeId = e.target.value;
                  console.log(seriesType);
                  return prev;
                })//e.target.value
              }}

            >
            </Radio.Group>
          </Form.Item>

          <div style={{ display: "flex", justifyContent: "right" }}>
            <Button color="primary" variant="solid" size="large" onClick={onSubmit}>
              发布
            </Button>
            <Button variant="solid" size="large" style={{ marginLeft: "10px" }}>
              文件上传
            </Button>
          </div>


        </Form>
      </div>
    </>
  )
}
export default Upload;